const mysql = require('mysql')
const formidable = require('formidable')
const path = require('path')

const connection = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'mybase',
});

module.exports = {
  getalldata: function (req, res) {
    let sql = 'select * from mybase where isdel=0';
    //渲染数据库页面
    connection.query(sql, (err, results) => {
      if (err) res.json({ code: 400, msg: '查询失败' });
      res.json({
        code: 200,
        msg: '查询成功',
        data: results,
      })
    })
  },
  //上传图片业务
  uploadFile: function (req, res) {
    const form = formidable({
      //上传到服务器的路径
      uploadDir: __dirname + '/public/images',
      //是否保留扩展名
      keepExtensions: true,
    })
    //接收过来的req参数返回
    form.parse(req, (err, fielbs, files) => {
      if (err) res.join({ code: 200, msg: '上传失败' })
      res.json({ code: 200, msg: '上传成功', img: path.basename(files.img.path) });
    })
  },
  //点击新增业务
  add: function (req, res) {
    let sql = 'insert into mybase set ?'
    connection.query(sql, req.body, (err) => {
      console.log(req.body.name);
      if (!req.body.name) {
        return res.json({ code: 400, msg: '检查name属性' })
      }
      if (err) res.json({ code: 500, msg: '新增失败' })
      else res.json({ code: 200, msg: '新增成功' })
    })
  },
  //点击修改
  getHeroById: function (req, res) {
    let id = req.query;
    let sql = 'select * from mybase where id=' + id.id;
    connection.query(sql, (err, results) => {
      if (err) res.json({ code: 500, msg: '获取数据失败' })
      res.json({ code: 200, msg: '获取成功', data: results[0] })
    })
  },
  //点击编辑
  edit: function (req, res) {
    if (!req.body.id) return res.json({ code: 400, msg: '检查id属性' })
    let sql = 'update mybase set ? where id=?'
    connection.query(sql, [req.body, req.body.id], (err) => {
      if (err) res.json({ code: 500, msg: '修改失败' })
      res.json({ code: 200, msg: '修改成功' })
    })
  }
}
